package test.views;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Hashtable;

import utils.ShowException;

import com.example.android.google.apis.R;

import docks.Dock;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class GetHtml extends Activity {

    public void onCreate(Bundle icicle) {

	super.onCreate(icicle);
	setContentView(R.layout.testgethtml);
	TextView tv = (TextView) findViewById(R.id.textView1);
	String html = null;

	try {
	    html = doConnection("http://www.bicing.cat/localizaciones/localizaciones.php?TU5fTE9DQUxJWkFDSU9ORVM%3D&MQ%3D%3D");
	} catch (Exception e) {

//	    ShowException.show(this, e);
	}
	String xml = extractXml(html, "<Document>", "</Document>");
	xmlparser.SaxParser sax = new xmlparser.SaxParser(xml);

	try {
	    sax.parseBicingState();
	} catch (Exception e) {

	    ShowException.show(this, e);
	}

	Hashtable<Integer, Dock> dockList = sax.getDockList();

	String result = "";
	if (dockList != null)
	    
	    for (Dock d : dockList.values()) {

		result += d.getIdDock();
		result += " ";
		result += d.getAddress();
		result += " ";
		result += d.getAvailableBikes();
		result += " ";
		result += d.getFreeSlots();
		result += " ";
		result += d.getLatitude();
		result += " ";
		result += d.getLongitude();
		result += "\n";
	    }
	else {

	    result += "LLISTA NULA!!!!";
	}

	tv.setText("CONTENT: \n" + result);

    }

    private String extractXml(String html, String initTag, String endTag) {

	int beginIndex = html.indexOf(initTag);
	int endIndex = html.indexOf(endTag);
	html = html.substring(beginIndex, endIndex + endTag.length());

	return html;
    }
    
    private String doConnection(String URL) throws Exception {

	String html;

	URL web = new URL(URL);
	URLConnection conn = web.openConnection();
	String encoding = conn.getContentEncoding();
	if(encoding == null)
	        encoding = "ISO-8859-1";
	
	BufferedReader in = new BufferedReader(new InputStreamReader(
		conn.getInputStream(), encoding));
	StringBuffer inputResponse = new StringBuffer();
	String inputLine;
	while ((inputLine = in.readLine()) != null) {

	    inputResponse.append(inputLine);
	}
	in.close();

	html = inputResponse.toString();

	return html;
    }
}
